package org.xxpay.agent.order.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xxpay.agent.common.ctrl.BaseController;
import org.xxpay.agent.common.service.RpcCommonService;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.AgentInfo;
import org.xxpay.core.entity.PayOrder;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

@Controller
@RequestMapping(Constant.AGENT_CONTROLLER_ROOT_PATH + "/pay_order")
public class PayOrderController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;

    /**
     * 查询单条支付记录
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String payOrderId = getStringRequired(param, "payOrderId");
        Long agentId = getUser().getId();
        PayOrder queyrPayOrder = new PayOrder();
        queyrPayOrder.setAgentId(agentId);
        queyrPayOrder.setPayOrderId(payOrderId);
        PayOrder payOrder = rpcCommonService.rpcPayOrderService.find(queyrPayOrder);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(payOrder));
    }

    /**
     * 支付订单记录列表
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer page = getInteger(param, "page");
        Integer limit = getInteger(param, "limit");
        PayOrder payOrder = getObject(param, PayOrder.class);
        payOrder.setAgentId(getUser().getId());
        // 订单起止时间
        Date createTimeStart = null;
        Date createTimeEnd = null;
        String createTimeStartStr = getString(param, "createTimeStart");
        if(StringUtils.isNotBlank(createTimeStartStr)) createTimeStart = DateUtil.str2date(createTimeStartStr);
        String createTimeEndStr = getString(param, "createTimeEnd");
        if(StringUtils.isNotBlank(createTimeEndStr)) createTimeEnd = DateUtil.str2date(createTimeEndStr);

        int count = rpcCommonService.rpcPayOrderService.count(payOrder, createTimeStart, createTimeEnd);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<PayOrder> payOrderList = rpcCommonService.rpcPayOrderService.select(
                (getPageIndex(page) -1) * getPageSize(limit), getPageSize(limit), payOrder, createTimeStart, createTimeEnd);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(payOrderList, count));
    }


    /**
     * 总代理下的代理的商户订单信息支付订单记录列表
     * @return
     */
    @RequestMapping("/agentmchorderlist")
    @ResponseBody
    public ResponseEntity<?> agentmchorderlist(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer page = getInteger(param, "page");
        Integer limit = getInteger(param, "limit");
        PayOrder payOrder = getObject(param, PayOrder.class);
        // 订单起止时间
        Date createTimeStart = null;
        Date createTimeEnd = null;
        String createTimeStartStr = getString(param, "createTimeStart");
        if(StringUtils.isNotBlank(createTimeStartStr)) createTimeStart = DateUtil.str2date(createTimeStartStr);
        String createTimeEndStr = getString(param, "createTimeEnd");
        if(StringUtils.isNotBlank(createTimeEndStr)) createTimeEnd = DateUtil.str2date(createTimeEndStr);
        //查询总代理下的代理商信息
        AgentInfo agentInfo = getObject(param, AgentInfo.class);
        agentInfo.setParentAgentId(getUser().getId());
        String agentId = null;
        int count = 0;
        List<PayOrder> payOrderList = new ArrayList<>();
        List<Map> agentInfoList = rpcCommonService.rpcAgentInfoService.selectInfoAndAccount(0, 10000, agentInfo);
        System.out.println("============="+agentInfoList.size()+"========="+agentInfoList.toString());
        for (Map a:agentInfoList) {
             agentId = String.valueOf(a.get("agentId"));
             payOrder.setAgentId(Long.valueOf(agentId));
             int  count1 = rpcCommonService.rpcPayOrderService.count(payOrder, createTimeStart, createTimeEnd);
            System.out.println("======count1======"+count1);
             if(count1 > 0) {
                 List<PayOrder> payOrderList1 = rpcCommonService.rpcPayOrderService.select(
                        (getPageIndex(page) -1) * getPageSize(limit), getPageSize(limit), payOrder, createTimeStart, createTimeEnd);
                 if(payOrderList1.size()>0) {
                     for (PayOrder p:payOrderList1) {
                         payOrderList.add(p);
                     }
                }

            }
            count=count+count1;
        }

        if(count==0){
            return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        }
        System.out.println("-------------"+count);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(payOrderList, count));
    }
    /**
     * 查询订单统计数据
     * @return
     */
    @RequestMapping("/count")
    @ResponseBody
    public ResponseEntity<?> count(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String payOrderId = getString(param, "payOrderId");
        String mchOrderNo = getString(param, "mchOrderNo");
        Long productId = getLong(param, "productId");
        Long mchId = getLong(param, "mchId");
        Byte productType = getByte(param, "productType");
        Long angentId = getUser().getId();

        // 订单起止时间
        String createTimeStartStr = getString(param, "createTimeStart");
        String createTimeEndStr = getString(param, "createTimeEnd");
        Map allMap = rpcCommonService.rpcPayOrderService.count4All(angentId, mchId, productId, payOrderId, mchOrderNo, productType, createTimeStartStr, createTimeEndStr);
        Map successMap = rpcCommonService.rpcPayOrderService.count4Success(angentId, mchId, productId, payOrderId, mchOrderNo, productType, createTimeStartStr, createTimeEndStr);
        Map failMap = rpcCommonService.rpcPayOrderService.count4Fail(angentId, mchId, productId, payOrderId, mchOrderNo, productType, createTimeStartStr, createTimeEndStr);

        JSONObject obj = new JSONObject();
        obj.put("allTotalCount", allMap.get("totalCount"));                         // 所有订单数
        obj.put("allTotalAmount", allMap.get("totalAmount"));                       // 总金额
        obj.put("successTotalCount", successMap.get("totalCount"));                 // 成功订单数
        obj.put("successTotalAmount", successMap.get("totalAmount"));               // 成功金额
        obj.put("successTotalMchIncome", successMap.get("totalMchIncome"));         // 成功商户收入
        obj.put("successTotalAgentProfit", successMap.get("totalAgentProfit"));     // 成功代理商利润
        obj.put("failTotalCount", failMap.get("totalCount"));                       // 未完成订单数
        obj.put("failTotalAmount", failMap.get("totalAmount"));                     // 未完成金额
        return ResponseEntity.ok(XxPayResponse.buildSuccess(obj));
    }

//    @RequestMapping("/agentMchcount")
//    @ResponseBody
//    public ResponseEntity<?> agentMchcount(HttpServletRequest request) {
//        JSONObject param = getJsonParam(request);
//        PayOrder payOrder = getObject(param, PayOrder.class);
//
//        Date createTimeStart = null;
//        Date createTimeEnd = null;
//        String createTimeStartStr = getString(param, "createTimeStart");
//        if(StringUtils.isNotBlank(createTimeStartStr)) createTimeStart = DateUtil.str2date(createTimeStartStr);
//        String createTimeEndStr = getString(param, "createTimeEnd");
//        if(StringUtils.isNotBlank(createTimeEndStr)) createTimeEnd = DateUtil.str2date(createTimeEndStr);
//
//        String payOrderId = getString(param, "payOrderId");
//        String mchOrderNo = getString(param, "mchOrderNo");
//        Long productId = getLong(param, "productId");
//        Long mchId = getLong(param, "mchId");
//        Byte productType = getByte(param, "productType");
//        Long parentangentId = getUser().getId();
//        //查询总代理下的代理商信息
//        AgentInfo agentInfo = getObject(param, AgentInfo.class);
//        agentInfo.setParentAgentId(parentangentId);
//        List<Map> agentInfoList = rpcCommonService.rpcAgentInfoService.selectInfoAndAccount(1, 10000, agentInfo);
//        String agentId= "0";
//        Map allMap = new HashMap();
//        Map successMap = new HashMap();
//        Map failMap = new HashMap();
//        Long allTotalCount=0l;
//        BigDecimal allTotalAmount =new BigDecimal(0);
//        Long successTotalCount=0l;
//        BigDecimal successTotalAmount =new BigDecimal(0);
//        BigDecimal successTotalMchIncome =new BigDecimal(0);
//        BigDecimal successTotalAgentProfit =new BigDecimal(0);
//        Long failTotalCount=0l;
//        BigDecimal failTotalAmount =new BigDecimal(0);
//
//
//        for (Map a:agentInfoList) {
//            agentId = String.valueOf(a.get("agentId"));
//            allMap = rpcCommonService.rpcPayOrderService.count4All(Long.valueOf(agentId), mchId, productId, payOrderId, mchOrderNo, productType, createTimeStartStr, createTimeEndStr);
//            successMap = rpcCommonService.rpcPayOrderService.count4Success(Long.valueOf(agentId), mchId, productId, payOrderId, mchOrderNo, productType, createTimeStartStr, createTimeEndStr);
//            failMap = rpcCommonService.rpcPayOrderService.count4Fail(Long.valueOf(agentId), mchId, productId, payOrderId, mchOrderNo, productType, createTimeStartStr, createTimeEndStr);
//            allTotalCount = (Long) allMap.get("totalCount")+allTotalCount;
//            if(allMap.get("totalAmount")!=null) {
//                allTotalAmount = allTotalAmount.add(objectConvertBigDecimal(allMap.get("totalAmount")));
//            }
//            successTotalCount = (Long)successMap.get("totalCount")+successTotalCount;
//            successTotalAmount = successTotalAmount.add(objectConvertBigDecimal(successMap.get("totalAmount")));
//            successTotalMchIncome =successTotalMchIncome.add(objectConvertBigDecimal(successMap.get("totalMchIncome")));
//            successTotalAgentProfit =  successTotalAgentProfit.add(objectConvertBigDecimal(successMap.get("totalAgentProfit")));
//            failTotalCount = (Long)failMap.get("totalCount")+failTotalCount;
//            failTotalAmount =failTotalAmount.add(objectConvertBigDecimal(failMap.get("totalAmount")));
//
//        }
//
//        JSONObject obj = new JSONObject();
//        obj.put("allTotalCount", allTotalCount);                         // 所有订单数
//        obj.put("allTotalAmount", allTotalAmount);                       // 总金额
//        obj.put("successTotalCount", successTotalCount);                 // 成功订单数
//        obj.put("successTotalAmount", successTotalAmount);               // 成功金额
//        obj.put("successTotalMchIncome", successTotalMchIncome);         // 成功商户收入
//        obj.put("successTotalAgentProfit", successTotalAgentProfit);     // 成功代理商利润
//        obj.put("failTotalCount", failTotalCount);                       // 未完成订单数
//        obj.put("failTotalAmount", failTotalAmount);                     // 未完成金额
//        return ResponseEntity.ok(XxPayResponse.buildSuccess(obj));
//    }

    public static BigDecimal objectConvertBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                 ret = (BigDecimal) value;
            } else if (value instanceof String) {
                 ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                 ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                 ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                 throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }
}